<template>
  <div class="main-wrapper">
    <div class="breadcrumb">
      <div style="flex: 1">
        <span class="breadcrumb-item" @click="closeForm('')" v-if="portraitType === 'judicial_case'">案件画像</span>
        <span class="breadcrumb-item" @click="closeForm('')" v-if="portraitType === 'criminal_suspect'">嫌疑人画像</span>
        <span class="breadcrumb-item" @click="closeForm('')" v-if="portraitType === 'victim'">受害人画像</span>
        <i class="breadcrumb-item-icon el-icon-arrow-right"></i>
        <span class="breadcrumb-item">新增画像</span>
      </div>
      <el-button type="primary" :loading="btnLoading" @click="saveImage" v-show="step === 2">保存为画像报告</el-button>
    </div>
    <div class="first-wrapper" v-show="step === 1">
      <div class="steps-wrapper">
        <div>
          <img class="icon" src="@/assets/img/icon-step1.png" alt="">
          <p>添加想要分析的画像群</p>
        </div>
        <img src="@/assets/img/icon-next-arrow.png" class="icon-arrow" alt="">
        <div>
          <img class="icon" src="@/assets/img/icon-step2.png" alt="">
          <p>添加画像指标</p>
        </div>
        <img src="@/assets/img/icon-next-arrow.png" class="icon-arrow" alt="">
        <div>
          <img class="icon" src="@/assets/img/icon-step3.png" alt="">
          <p>保存并完成画像报告创建</p>
        </div>
      </div>
      <el-button @click="handleAddImage" type="primary" class="plain-btn add-img-btn">添加画像群</el-button>
    </div>
    <div class="second-wrapper" id="pdfWrapper" v-show="step === 2" v-loading="loading">
      <div class="image-case-group">
        <div class="title-wrapper">
          <span class="title">画像案件群</span>
          <!--          <span>
                      <el-button type="primary" size="small" class="plain-btn">添加对比人群</el-button>
                      <el-button type="primary" size="small" class="plain-btn">添加对比人群</el-button>
                    </span>-->
        </div>
        <div class="detail-wrapper clearfix">
          <span class="left btn">{{ caseGroupData.name || '' }}</span>
          <template v-if="portraitType === 'judicial_case'">
            <span class="left" style="margin-left: 30px">2024所有案件：<span class="text">{{
                infoNumber.num
              }}</span> 起</span>
            <span class="left" style="margin-left: 30px">目标案件群 <span class="text"
                                                                     v-if="infoNumber.rate">{{ infoNumber.rate * 100 }}%</span></span>
          </template>
          <template v-if="portraitType === 'criminal_suspect'">
            <span class="left" style="margin-left: 30px">全量嫌疑人画像：<span class="text">{{ infoNumber.num }}</span> 人</span>
            <span class="left" style="margin-left: 30px">占全部嫌疑人 <span class="text"
                                                                      v-if="infoNumber.rate">{{ infoNumber.rate * 100 }}%</span></span>
          </template>
          <template v-if="portraitType === 'victim'">
            <span class="left" style="margin-left: 30px">全量受害人画像：<span class="text">{{ infoNumber.num }}</span> 人</span>
            <span class="left" style="margin-left: 30px">占全部受害人 <span class="text"
                                                                      v-if="infoNumber.rate">{{ infoNumber.rate * 100 }}%</span></span>
          </template>
          <el-button @click="handleDetail" type="text" class="right">详情</el-button>
        </div>
      </div>
      <div class="image-case-group">
        <div class="title-wrapper">
          <span class="title">画像信息</span>
          <span>
            <el-button @click="handleAddGroup" type="primary" size="small" class="plain-btn">添加分组</el-button>
            <el-button @click="handleAddImageInfo" type="primary" size="small" class="plain-btn"
                       v-if="portraitType !== 'victim1111111'">添加画像信息</el-button>
          </span>

        </div>
        <div class="image-info-list" v-if="portraitType === 'victim1111111'">
          <div @click="handleAddImageInfo" class="image-info-item item-add">
            <i class="el-icon-plus"></i>
            <span>添加画像信息</span>
          </div>
          <div class="image-info-item" v-for="(item,index) in imageInfoList" :key="index">
            <div class="tit">{{ item.info.dimension1FieldDesc }}</div>
            <p>
              <span v-for="(item,key) in item.dataList" :key="key">第{{ key + 1 }}个维度</span>
            </p>
            <div class="bot">
              <div>画像模板名称</div>
              <el-button size="small" class="plain-btn">使用</el-button>
            </div>
          </div>
        </div>
        <div class="box-wrapper" v-else>
          <div class="item-box" v-for="(item,index) in imageInfoList" :key="index">
            <div class="item-title-box">
              <span class="title">{{ item.info.dimension1FieldDesc }}</span>
              <!--              <el-button @click="handleEditImageInfo(item)" class="btn-blue" icon="el-icon-delete" plain size="small">编辑</el-button>-->
              <el-button @click="handleDelItem(item)" class="btn-red" icon="el-icon-delete" plain size="small">删除
              </el-button>
            </div>
            <div class="select-box">
              <el-select
                  v-model="item.pageSize"
                  class="select-item"
                  placeholder="请选择"
                  @change="handleSizeChange(item,index)"
              >
                <el-option :value="10" label="前10项"></el-option>
                <el-option :value="20" label="前20项"></el-option>
                <el-option :value="9999" label="全部项"></el-option>
              </el-select>
              <el-select
                  v-model="item.echartsOption.series[0].type"
                  @change="chartsTypeChange($event,item,index)"
                  class="select-item"
                  placeholder="请选择"
              >
                <el-option value="bar" label="条形图"></el-option>
                <el-option value="pie" label="饼状图" :disabled="item.isStack"></el-option>
                <el-option value="treemap" label="色块图" :disabled="item.isStack"></el-option>
              </el-select>
            </div>
            <div class="chart" :id="`myChart${index}`" :style="{ width: '100%', height: '460px' }"></div>
          </div>
        </div>
      </div>
    </div>

    <!--添加画像目标案件群-->
    <case-group-drawer
        :visible="visible"
        :mode="mode"
        :portraitType="portraitType"
        @close="closeDrawer"
        ref="caseGroup"
    >
    </case-group-drawer>
    <image-info-dialog
        ref="imageInfo"
        :visible="imageInfoVisible"
        :mode="mode"
        :portraitType="portraitType"
        :caseGroupData="caseGroupData"
        @close="closeDialog"
    ></image-info-dialog>
    <add-group-dialog
        :visible="addGroupVisible"
        :portraitType="portraitType"
        :caseGroupData="caseGroupData"
        :imageInfoList="imageInfoList"
        @close="closeDialog"
    ></add-group-dialog>
  </div>
</template>

<script>
import {sandbox, htmlToPdf} from "@/libs/util";
import CaseGroupDrawer from "./CaseGroupDrawer";
import ImageInfoDialog from "./ImageInfoDialog";
import AddGroupDialog from "./AddGroupDialog";

let echarts = require("echarts/lib/echarts");
// 引入柱状图组件
require("echarts/lib/chart/bar");
// 引入矩形图组件
require("echarts/lib/chart/treemap");
// 引入饼图组件
require("echarts/lib/chart/pie");
// 引入提示框和title组件
require("echarts/lib/component/tooltip");
// 引入提示框和title组件
require("echarts/lib/component/legend");

require("echarts/lib/component/legendScroll");

export default {
  name: "AddImageStep",
  components: {AddGroupDialog, ImageInfoDialog, CaseGroupDrawer},
  props: {
    portraitType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      step: 1,
      mode: '',
      loading: false,
      btnLoading: false,
      visible: false,
      imageInfoVisible: false,
      addGroupVisible: false,
      infoDetail: true,
      imageInfoList: [],
      infoNumber: {},
      caseGroupData: {},
      portraitId: '',
      echartsOption: {
        tooltip: {
          trigger: 'item',
        },
        legend: {
          top: 10,
          padding: [0, 0, 20, 0],
          icon: "circle",
          left: 'center',
          type: 'scroll',  //legend要多，进行分页处理
          data: []
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          show: false,
          data: []
        },
        yAxis: {
          show: false,
          type: 'value'
        },
        color: ['#3399FF', '#63DAAB', '#FFC51C', '#FA862A', '#7666FA', '#75CBED', '#9A67BD', '#657798', '#2A9A99', '#FF9EC6'],
        series: [
          {
            type: 'pie',
            breadcrumb: {show: false},
            center: ['50%', '50%'],
            showBackground: true,
            barWidth: '60%',
            barMaxWidth: '60',
            data: [],
          }
        ]
      }
    }
  },
  methods: {
    closeForm(isReload) {
      this.step = 1
      this.imageInfoList = []
      this.infoNumber = {}
      this.caseGroupData = {}
      this.portraitId = ''
      this.$emit('back', isReload)
    },
    closeDrawer(value) {
      this.visible = false
      if (value) {
        this.step = 2
        this.portraitId = value.id
        this.getCountNumber()
        this.getDetail()
      }
    },
    async closeDialog(value) {
      this.imageInfoVisible = false
      this.addGroupVisible = false
      if (value) {
        await this.getStatistics()
        this.initChartsAll()
      }
    },
    handleDetail() {
      this.$refs.caseGroup.edit(this.caseGroupData)
      this.visible = true
      this.mode = 'edit'
    },
    // 获取详情
    getDetail() {
      this.$api.api_urcap_portrait_get({
        param: {id: this.portraitId},
      }).then(res => {
        this.caseGroupData = res.data
      })
    },
    // 获取统计
    getCountNumber() {
      this.$api.api_urcap_portrait_baseInfoCount({
        param: {portraitId: this.portraitId},
      }).then(res => {
        this.infoNumber = res.data
      })
    },
    // 获取图表
    async getStatistics() {
      this.loading = true
      await this.$api.api_urcap_portraitInfo_getByPortraitId({
        param: {portraitId: this.portraitId,},
      }).then(res => {
        let data = res.data || []
        this.imageInfoList = data.map((ele) => {
          let isStack = false
          if (ele.dataList.find(k => k.dimension2)) {
            isStack = true
          }
          return {
            dataList: ele.dataList.slice(0, 10),
            dataListAll: ele.dataList,
            info: ele.info,
            pageSize: 10,
            isStack: isStack,
            echartsOption: sandbox(this.echartsOption),
          }
        })
      }).finally(() => {
        this.loading = false
      })
    },
    handleSizeChange(data, index) {
      data.dataList = data.dataListAll.slice(0, data.pageSize)
      this.initCharts(data, index)
    },
    async SetData(row) {
      this.portraitId = row.id
      this.step = 2
      this.getDetail()
      this.getCountNumber()
      await this.getStatistics()
      this.initChartsAll()
    },
    // 循环初始化所有图表数据
    initChartsAll() {
      this.imageInfoList.forEach((item, index) => {
        if (item?.dataList?.length) {
          this.initCharts(item, index)
        }
      })
    },
    // 根据数据绘制相应图表
    initCharts(item, index) {
      let dataList = item.dataList.map((ele) => {
        return {
          value: ele.num,
          name: ele.dimension1
        }
      })
      let dataList2 = item.dataList.filter(e => e.dimension2).map((ele) => {
        return {
          value: ele.num,
          name: ele.dimension2
        }
      })
      let legendData = dataList.map(ele => ele.name)
      let echartsOption = sandbox(item.echartsOption)
      if (dataList2?.length) {
        const nameList = Array.from(new Set(dataList2.map(ele => ele.name)));
        const series = nameList.map((name) => {
          return {
            name,
            type: 'bar',
            stack: 'same',
            barWidth: '60%',
            barMaxWidth: '60',
            label: {
              show: true,
            },
            data: item.dataList.filter((d) => name === d.dimension2).map(e => e.num)
          };
        });
        const newArray = Array.from(new Set(legendData));
        echartsOption.legend = {}
        echartsOption.tooltip = {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        }
        echartsOption.xAxis = [
          {
            type: 'category',
            data: newArray
          }
        ]
        echartsOption.yAxis = [
          {
            type: 'value',
            axisLine: {//坐标轴轴线
              show: false
            },
            axisTick: {//坐标轴刻度
              show: false
            },
          }
        ]
        echartsOption.series = series
      } else {
        echartsOption.legend.data = legendData
        echartsOption.series[0].data = dataList
        echartsOption.xAxis.show = false
        echartsOption.yAxis.show = false
        echartsOption.label = {formatter: '{b}'}
        if (echartsOption.series[0].type === 'pie') {
          // console.log('echartsOption',echartsOption)
          echartsOption = {
            ...echartsOption,
            label: {
              formatter: '{b}：{c}  {d}%'
            },
          }
        }
        if (echartsOption.series[0].type === 'bar') {
          echartsOption = {
            ...echartsOption,
            xAxis: {
              type: 'category',
              show: true,
              data: legendData
            },
            yAxis: {
              show: true,
              type: 'value'
            },
          }
        }
      }

      item.echartsOption = echartsOption
      this.$nextTick(() => {
        this.drawCharts(`myChart${index}`, echartsOption)
      })
    },
    // 图标类型切换重绘图表
    chartsTypeChange(val, data, index) {
      this.$nextTick(() => {
        this.initCharts(data, index)
      })
    },
    handleAddImage() {
      this.mode = 'add'
      this.visible = true
    },
    handleAddGroup() {
      this.addGroupVisible = true
    },
    handleAddImageInfo(row) {
      this.imageInfoVisible = true
      this.mode = 'add'
      this.$refs.imageInfo.form.portraitId = this.portraitId
    },
    handleEditImageInfo(row) {
      this.imageInfoVisible = true
      this.mode = 'edit'
      this.$refs.imageInfo.edit(row)
    },
    drawCharts(ele, echartsOption) {
      if (!document.getElementById(ele)) return;
      let myChart = echarts.init(document.getElementById(ele));
      // 绘制图表
      myChart.setOption(echartsOption);
    },
    // 转pdf并上传
    async saveImage() {
      let file = await htmlToPdf('pdfWrapper', '画像报告')
      let form = new FormData()
      form.append('attributeExplain', '画像报告')
      form.append('file', file)
      this.btnLoading = true
      this.$api
          .api_urcap_fileController_upload({
            body: form,
          })
          .then(res => {
            this.bindPdf(res.data.attachmentId)
          })
          .catch(() => {
            this.btnLoading = false
          })
    },
    bindPdf(attachmentId) {
      this.$api.api_urcap_portraitReport_add({
        body: {
          attachmentId,
          portraitId: this.portraitId
        },
        config: {showMsg: true}
      }).then(res => {
        this.closeForm('reload')
      }).finally(() => {
        this.btnLoading = false
      })
    },

    async handleDelItem(row) {
      this.$confirm('确认删除该数据？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$api
            .api_urcap_portraitInfo_delete({param: {id: row.info.id}})
            .then(async () => {
              await this.getStatistics()
              this.initChartsAll()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            })
      })
    },

  },
  beforeDestroy() {
    let myChart =
        document.getElementById("myChart") &&
        echarts.init(document.getElementById("myChart"));
    myChart && myChart.clear();
  },
}
</script>

<style scoped lang="scss">
.main-wrapper {
  max-width: calc(100vw - 220px);
  height: 100%;
  overflow-y: auto;
  padding: 15px 15px 0 15px;
  box-sizing: border-box;
}

.first-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: calc(100% - 140px);
  padding: 20px;
  border-radius: 8px;
  border: 2px solid #FFFFFF;

  .steps-wrapper {
    display: flex;
    align-items: center;

    .icon-arrow {
      margin: 0 50px;
    }

    p {
      line-height: 1;
      font-weight: 500;
      font-size: 24px;
      color: #333333;
      text-align: center;
    }
  }

  .add-img-btn {
    margin-top: 120px;
    width: 280px;
    height: 72px;
    font-size: 24px
  }
}

.title-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  line-height: 1;

  .title {
    height: 18px;
    line-height: 1;
    border-left: 4px solid #0B085F;
    padding-left: 16px;
    font-size: 18px;
  }
}

.image-case-group {
  padding: 20px;
  background: rgba(255, 255, 255, 0.502);
  border: 2px solid #FFFFFF;
  border-radius: 8px;
  margin-top: 20px;

  .detail-wrapper {
    padding: 15px 12px;
    background: #FFFFFF;
    border-radius: 10px 10px 10px 10px;
    border: 1px solid #D9D9D9;
    line-height: 32px;
    margin-top: 30px;

    .btn {
      height: 32px;
      line-height: 32px;
      background: #0B085F;
      border-radius: 6px;
      color: #FFFFFF;
      padding: 0 8px;
    }

    .text {
      font-size: 24px;
      color: #0B085F;
    }
  }
}

.image-info-list {
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  padding: 0 60px;
  margin-top: 20px;

  .image-info-item {
    position: relative;
    width: calc(25% - 25px);
    height: 220px;
    background: linear-gradient(180deg, #EFF7FF 0%, #FFFFFF 100%);
    border-radius: 8px;
    border: 1px solid #DCE1E4;
    font-size: 14px;
    color: #666666;
    margin-right: 30px;
    padding: 15px 0;

    &:nth-child(4n) {
      margin-right: 0;
    }

    .tit {
      font-size: 16px;
      padding: 0 24px;
    }

    p {
      padding: 0 24px;
      line-height: 20px;
    }

    .bot {
      box-sizing: border-box;
      width: 100%;
      position: absolute;
      bottom: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      border-top: 1px solid #DCE1E4;
    }
  }

  .item-add {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background: #FFFFFF;
    border: 1px solid #DCE1E4;
    color: #999999;

    .el-icon-plus {
      font-size: 40px;
      margin-bottom: 10px;
    }
  }
}

.box-wrapper {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20px;

  .item-box {
    position: relative;
    width: calc(50% - 10px);
    height: 583px;
    background: #FFFFFF;
    border-radius: 10px;
    border: 1px solid #D9D9D9;
    margin-right: 16px;
    margin-bottom: 16px;

    &:nth-child(2n) {
      margin-right: 0;
    }

    .item-title-box {
      display: flex;
      align-items: center;
      padding: 16px;

      .title {
        flex: 1;
        font-weight: 500;
        font-size: 18px;
        color: #000066;
        line-height: 18px;
      }

      .btn-blue {
        color: #2774F4;
        border-color: #2774F4;
      }

      .btn-red {
        color: #F42626;
        border-color: #F42626;
      }
    }

    .select-box {
      padding: 0 16px;
      display: flex;

      .select-item {
        width: 120px;
        margin-right: 20px;
      }
    }
  }

  .chart {
    width: 100%;
    box-sizing: border-box;
    padding: 5px 20px;
  }

}

@media screen and (max-width: 1500px) {
  .first-wrapper {
    .steps-wrapper {
      .icon{
        width: 240px;
        height: 240px;
      }
      p {
        font-size: 20px;
      }
    }

    .icon-arrow{
      margin: 0 20px;
    }
  }
}

@media screen and (max-width: 1300px) {
  .first-wrapper {
    .steps-wrapper {
      .icon{
        width: 160px;
        height: 160px;
      }
      p {
        font-size: 16px;
      }
    }

    .icon-arrow{
      margin: 0 10px;
    }
  }
}

</style>

<style scoped>
/deep/ .select-item .el-input__inner {
  border: 1px solid #0B085F;
  color: #0B085F;
}
</style>